from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from django.urls import reverse

# 购物车信息管理
def add(request,pid):
    '''添加购物车'''
    product = request.session['productlist'][pid]
    product['num'] = 1
    cartlist = request.session.get("cartlist",{})
    #判断购物车中是否已存在要购买的商品
    if pid in cartlist:
        cartlist[pid]['num'] += product['num'] #累加购买量
    else:
        cartlist[pid] = product
    #将购物车中的商品信息放回到session中
    request.session['cartlist'] = cartlist
    #跳转查看购物车
    return redirect(reverse('web_index'))

def delete(request,pid):
    '''删除购物车中的商品'''
    cartlist = request.session['cartlist']
    del cartlist[pid]
    request.session['cartlist'] = cartlist
    return redirect(reverse('web_index'))

def clear(request):
    '''清空购物车'''
    request.session['cartlist'] = {}
    return redirect(reverse('web_index'))

def change(request):
    '''购物车信息修改'''
    cartlist = request.session['cartlist']
    shopid = request.GET.get("pid",0)
    num = int(request.GET.get('num',1))
    if num < 1:
        num = 1
    cartlist[shopid]['num'] = num
    request.session['cartlist'] = cartlist
    return redirect(reverse('web_index'))